<?php

require_once "Inweb/Controller/Action/Admin.php";

class Admin_StudioController extends Inweb_Controller_Action_Admin
{

	private $applicationdir;

	public function initAdmin()
	{
		$this->view->moduletitle="Inweb Studio";
		$this->view->submenu=array();
		
		$this->checkAdminAccess('admin.system.studio');
	}
	
	public function indexAction()
	{
		$mod = $this->_db->fetchAssoc($this->_db->select()->from($this->__module)->order(array('module_name asc')));
		
		$pluginpath = $this->_config->applicationdir.'/modules/';
		$where = array();
		foreach($mod as $m){
			$file = $pluginpath . $m['module_name'] .'/forms/AdminForm.php';
			//echo $file;exit;
			if(file_exists($file)){
				$where[] = $m['module_id'];
			}
		}

		$wh = implode(',',$where);
		
		$dbselect=$this->_db->select()->from($this->__module)->where('module_id in ('.$wh.')')->order(array('module_name asc'));
		
		$paginator=$this->getPaginator($dbselect);
		$this->view->paginator=$paginator;
		
		//$form = $this->loadForm('studio');
		
		//$this->view->form = $form;
	}
	
	public function labelAction(){
		$this->view->moduletitle="Inweb Studio - Label";
		$module_id = intval($this->getRequest()->getParam('modid'));
		$mod = $this->_db->fetchRow( $this->_db->select()->from($this->__module)->where('module_id=?',$module_id)->limit(1) );
		
		//Save new label
		if(intval($this->getRequest()->getPost('saving')) == 1){
			
			$el = $this->getElementForm($mod['module_name']);
			$formElement = array();
			foreach($el as $k){
				$formElement[] = array('type' => $k->type,
										'name' => $k->getName(),
										'label' => $k->getLabel(),
										'size' => $k->size,
										'required' => $k->isRequired()
										);
			}
			
			$opt = explode('-',$mod['module_name']);
			$filename = '';
			foreach($opt as $f){
				$filename .= ucfirst($f);
			}
			$filename .= '_Form_Admin';
			
			$methodPrepareFormBody = '$elements = array(); 
										$translate= Zend_Registry::get(\'translate\');
									';
			
			foreach($formElement as $k){
				$k['label'] = $this->getRequest()->getPost($k['name']);
				$k['required'] = $k['required'] == 1 ? 1 : 0;
				$methodPrepareFormBody .= ' 
										$elements[] = array(
										\'type\'		=> \''.$k['type'].'\',
										\'name\'		=> \''.$k['name'].'\',
										\'label\'		=> $translate->_(\''.$k['label'].'\'),
										\'value\'		=> $val[\''.$k['name'].'\'],';
				
				if($k['size'] != ''){				
					$methodPrepareFormBody .= '
												\'size\'		=> '.$k['size'].',';
				}
									
				$methodPrepareFormBody .= '
											\'required\'	=> '.$k['required'].'
									); 
									';
			}
			$methodPrepareFormBody .= '$this->addNewElements($elements);';
			
			require_once 'Zend/CodeGenerator/Php/Class.php';
			require_once 'Zend/CodeGenerator/Php/Docblock.php';
			require_once 'Zend/CodeGenerator/Php/File.php';
			require_once 'Zend/CodeGenerator/Php/Method.php';
			
			$foo      = new Zend_CodeGenerator_Php_Class();
			$docblock = new Zend_CodeGenerator_Php_Docblock(array(
				'shortDescription' => 'Generated By Inweb Studio',
				'longDescription'  => '',
				'tags'             => array(
					array(
						'name'        => 'Modification',
						'description' => date('d-m-Y'),
					),
				),
			));
			$foo->setName($filename.' extends Inweb_Form')
			->setDocblock($docblock)
			->setMethods(array(
				new Zend_CodeGenerator_Php_Method(array(
				    'name' => 'prepareForm',
				    'body'       => $methodPrepareFormBody,
				    'parameters' => array(
										array('name' => 'val'),
									),
				)),
			));
			
			//echo $foo;exit;
			
			$file = new Zend_CodeGenerator_Php_File();
			$file->setRequiredFiles(array('Inweb/Form.php'));
			$file->setClasses(array($foo));
			
			$code = $file->generate();
			
			//Backup Old File
			$oldfile = $this->_config->applicationdir.'/modules/'.$mod['module_name'].'/forms/AdminForm.php';
			@copy($oldfile,$oldfile.'.backup');
			@unlink($oldfile);
			file_put_contents($oldfile, $code);
			
			$this->redirect(array('action'=>'index','controller' => 'studio'),'admin');
			exit;
			
		}
		
		$el = $this->getElementForm($mod['module_name']);
		$formElement = array();
		foreach($el as $k){
			$formElement[] = array('type' => $k->type,
									'name' => $k->getName(),
									'label' => $k->getLabel(),
									'size' => $k->size,
									'required' => $k->isRequired()
									);
		}
		
		$this->view->elm = $formElement;
		
		$this->view->submenu = array(
			'browse' => array('title' => 'Browse', 'url' => $this->_helper->Url->url(array('action'=>'index'),null), 'li-class' => 'admin-browse')
		);
	}
	
	private function getElementForm($module)
	{
		$opt = explode('-',$module);
		$filename = '';
		foreach($opt as $f){
			$filename .= ucfirst($f);
		}
		$filename .= '_Form_Admin';
		$file = $this->_config->applicationdir.'/modules/'.$module.'/forms/AdminForm.php';
		//echo $file;exit;
		if(is_file($file)){
			require_once $file;
			$cform = new $filename();
			$cform->prepareForm(array());
			//$form::getInstance();
			//print_r($cform->getElements());
			//exit;
			return $cform->getElements();
		}
		
		return array();
		
	}
	
	public function fieldAction(){
		$this->view->moduletitle="Inweb Studio - Field";
		
		$this->view->submenu = array(
			'browse' => array('title' => 'Browse', 'url' => $this->_helper->Url->url(array('action'=>'index'),null), 'li-class' => 'admin-browse'),
			'add' => array('title'	=> 'Add', 'url' => 'javascript:studioFieldAdd()', 'li-class' => 'admin-add'),
			'delete' => array('title'	=> 'Delete', 'url' => 'javascript:studioFieldDelete()', 'li-class' => 'admin-delete')
		);
		
		$module_id = intval($this->getRequest()->getParam('modid'));
		$mod = $this->_db->fetchRow( $this->_db->select()->from($this->__module)->where('module_id=?',$module_id)->limit(1) );
		
		//Save new label
		if(intval($this->getRequest()->getPost('saving')) == 1){
			
			//print_r($this->getRequest()->getPost('article_title'));
			//print_r($_POST);
			//exit;
			
			$opt = explode('-',$mod['module_name']);
			$filename = '';
			foreach($opt as $f){
				$filename .= ucfirst($f);
			}
			$filename .= '_Form_Admin';
			
			$methodPrepareFormBody = '$elements = array(); 
										$translate= Zend_Registry::get(\'translate\');
									';
			
			foreach($_POST as $v => $k){
				if($k["'name'"] != '' && $k["'type'"] != '1' && $k["'label'"] != ''){
					$methodPrepareFormBody .= ' 
											$elements[] = array(
											\'type\'		=> \''.$k["'type'"].'\',
											\'name\'		=> \''.$k["'name'"].'\',
											\'label\'		=> $translate->_(\''.$k["'label'"].'\'),
											\'value\'		=> $val[\''.$k["'name'"].'\'],';
				
					if($k["'size'"] != ''){				
						$methodPrepareFormBody .= '
													\'size\'		=> '.$k["'size'"].',';
					}
									
					$methodPrepareFormBody .= '
												\'required\'	=> '.$k["'required'"].'
										); 
										';
									
					$this->createdNewDbField($k["'name'"],$k["'type'"],$k["'required'"],$mod['module_name']);					
				}
			}
			$methodPrepareFormBody .= '$this->addNewElements($elements);';
			
			require_once 'Zend/CodeGenerator/Php/Class.php';
			require_once 'Zend/CodeGenerator/Php/Docblock.php';
			require_once 'Zend/CodeGenerator/Php/File.php';
			require_once 'Zend/CodeGenerator/Php/Method.php';
			
			$foo      = new Zend_CodeGenerator_Php_Class();
			$docblock = new Zend_CodeGenerator_Php_Docblock(array(
				'shortDescription' => 'Generated By Inweb Studio',
				'longDescription'  => '',
				'tags'             => array(
					array(
						'name'        => 'Modification',
						'description' => date('d-m-Y'),
					),
				),
			));
			$foo->setName($filename.' extends Inweb_Form')
			->setDocblock($docblock)
			->setMethods(array(
				new Zend_CodeGenerator_Php_Method(array(
				    'name' => 'prepareForm',
				    'body'       => $methodPrepareFormBody,
				    'parameters' => array(
										array('name' => 'val'),
									),
				)),
			));
			
			//echo $foo;exit;
			
			$file = new Zend_CodeGenerator_Php_File();
			$file->setRequiredFiles(array('Inweb/Form.php'));
			$file->setClasses(array($foo));
			
			$code = $file->generate();
			
			//Backup Old File
			$oldfile = $this->_config->applicationdir.'/modules/'.$mod['module_name'].'/forms/AdminForm.php';
			@copy($oldfile,$oldfile.'.backup');
			@unlink($oldfile);
			file_put_contents($oldfile, $code);
			
			$this->redirect(array('action'=>'index','controller' => 'studio'),'admin');
			exit;
			
		}
		
		$el = $this->getElementForm($mod['module_name']);
		$formElement = array();
		foreach($el as $k){
			$formElement[] = array('type' => $k->type,
									'name' => $k->getName(),
									'label' => $k->getLabel(),
									'size' => $k->size,
									'required' => $k->isRequired()
									);
		}
		
		$this->view->elm = $formElement;
	}

	public function createdNewDbField($name,$type,$req,$mod){
		$type = $type == 'text' ? 'VARCHAR(150)' : 'TEXT';
		$req = $req == 1 ? 'NOT NULL' : '';
		
		$tablename = strtolower(end(explode('-',$mod)));
		//$tablename = strtolower($table[intval(count($table) - 1)]);
		
		$query = "SHOW COLUMNS FROM ".$tablename." LIKE '".strtolower($name)."';";
		//echo $query;exit;
		$row = $this->_db->fetchAll($query);
		
		if(count($row) <= 0){
			$query = "ALTER TABLE ".$tablename." ADD `".strtolower($name)."` ".$type." ".$req.";";
			$this->_db->query($query);
		}
	}
	
	public function layoutAction()
	{
		$this->view->moduletitle="Inweb Studio - Layout";
		
		$this->view->submenu = array(
			'browse' => array('title' => 'Browse', 'url' => $this->_helper->Url->url(array('action'=>'index'),null), 'li-class' => 'admin-browse')
		);
		
		$module_id = intval($this->getRequest()->getParam('modid'));
		$mod = $this->_db->fetchRow( $this->_db->select()->from($this->__module)->where('module_id=?',$module_id)->limit(1) );
		
		$themedir = $this->_config->applicationdir.'/modules/'.$mod['module_name'].'/views/scripts/frontend/';
		
		//Save new layout
		if(intval($this->getRequest()->getPost('saving')) == 1){
			
			foreach($_POST as $p => $v){
				if($p != 'saving'){
					$filename = str_replace('_','.',$p);
					$oldfile = $themedir . $filename;
					@copy($oldfile,$oldfile.'.backup');
					//@unlink($oldfile);
					// open file  
					$fw = fopen($oldfile, 'w'); 
					$fb = fwrite($fw,$v);  
					fclose($fw); 
				}
			}
			
			$this->redirect(array('action'=>'index','controller' => 'studio'),'admin');
			exit;
			
		}
		
		$files = array();
		if ($handle = opendir($themedir)) {
			while (false !== ($entry = readdir($handle))) {
				$ext = end(explode('.',$entry));
				if ($entry != "." && $entry != ".." && $entry != ".svn" && $ext != "backup") {
				    $files[] = $entry;
				}
			}
			closedir($handle);
		}
		
		$data = array();
		
		foreach($files as $f){
			$fh = fopen($themedir.$f, "r"); 
			$content = fread($fh, filesize($themedir.$f)); 
			fclose($fh);
			$data[] = array('name' => $f, 'content' => $content);
		}
		
		$this->view->layout = $data;
	}	
}
